	package browser.service;

	import browser.dao.UserInfo;
	import java.io.*;
	import java.sql.*;
	import java.text.ParseException;
	import java.text.SimpleDateFormat;
	import java.util.ArrayList;
	import java.util.Calendar;
	import java.util.Map;
	import javax.servlet.*;
	import javax.servlet.http.*;

	/**
	 * Servlet that will insert one row into the specified table
	 *
	 */
	public class Insert extends HttpServlet {

		public static Connection conn;
		public static Statement stmt;

		public void doGet(HttpServletRequest request,
				HttpServletResponse response) throws ServletException,
				IOException {

			doPost(request, response);
		}

		public void doPost(HttpServletRequest request,
				HttpServletResponse response) throws ServletException,
				IOException {

			response.setContentType("text/html");
			PrintWriter out = response.getWriter();

			// Check if session is expired
			if (request.getSession(false) == null
					|| (Boolean) request.getSession(false).getAttribute(
							"expired") == true) {
				out.println("Session expired");
				return;
			}

			String[] uid = request.getParameterValues("uid");
			String[] uacc = request.getParameterValues("uAccess");
			String[] tname = request.getParameterValues("tName");

			try {
				Class.forName("oracle.jdbc.driver.OracleDriver");
			} catch (ClassNotFoundException e) {
				out.println("Error loading the Driver:" + e.getMessage());
				return;
			}

			Connection conn = null;
			UserInfo user = MyUtilities.getUserInfo(uid[0]);

			if ((user.getUaccess() == null)
					|| (!uacc[0].equals(user.getUaccess()))) {
				out.print("Please login first");
				return;
			}
			try {
				conn = DriverManager.getConnection("jdbc:oracle:thin:"
						+ user.getUid() + "/" + user.getPassword()
						+ "@oraserver.cs.luc.edu:1521:cs");
			} catch (SQLException e1) {
				out.println("Error connecting to Oracle:" + e1.getMessage());
				return;
			}
			if (conn == null) {
				out.println("Null Connection");
				return;
			}

			Statement stmt1 = null;
			PreparedStatement stmt2 = null;
			try {
				stmt1 = conn.createStatement();
			} catch (SQLException e) {
				out.println("createStatement " + e.getMessage());
				try {
					conn.close();
				} catch (SQLException e2) {
				}
				;
				return;
			}

			ResultSet rset = null;
			int result = -1;
			String errorMessage = "";
			String sql = "select * from " + tname[0];

			try {
				rset = stmt1.executeQuery(sql);

				sql = "insert into " + tname[0] + " values (";
				for (int i = 1; i <= rset.getMetaData().getColumnCount(); i++) {
					if (rset.getMetaData().getColumnTypeName(i).equals("DATE"))
						sql += "to_date(?,'YYYY-MM-DD HH24:MI:SS'),";
					else
						sql += "?,";
				}
				sql = sql.substring(0, sql.length() - 1) + ")";

				stmt2 = conn.prepareStatement(sql);

				String columnType = "";
				for (int i = 1; i <= rset.getMetaData().getColumnCount(); i++) {
					columnType = rset.getMetaData().getColumnTypeName(i);
					String[] insertVaules = request.getParameterValues(rset
							.getMetaData().getColumnName(i));
					String insertValue = insertVaules[insertVaules.length - 1];
					if (columnType.equals("CHAR")) {
						if (insertValue.equals(""))
							stmt2.setNull(i, Types.CHAR);
						else
							stmt2.setString(i, insertValue);
					} else if (columnType.equals("VARCHAR2")) {
						if (insertValue.equals(""))
							stmt2.setNull(i, Types.VARCHAR);
						else
							stmt2.setString(i, insertValue);
					} else if (columnType.equals("NUMBER")) {
						if (insertValue.equals(""))
							stmt2.setNull(i, Types.NUMERIC);
						else
							stmt2.setDouble(i, Double.parseDouble(insertValue));
					} else if (columnType.equals("DATE")) {
						if (insertValue.equals("")) {
							stmt2.setNull(i, Types.DATE);
						} else if (insertValue.equals("NOW")) {
							SimpleDateFormat sdf = new SimpleDateFormat(
									"yyyy-MM-dd HH:mm:ss");
							stmt2.setString(i, sdf.format(Calendar
									.getInstance().getTime()));
						} else {
							stmt2.setString(i, insertValue);
						}
					}

				}
				result = stmt2.executeUpdate();

			} catch (SQLException e) {
				errorMessage = e.getMessage();
			}

			if (result == 1) {
				response
						.sendRedirect("/DatabaseBrowser/QueryTable?uid="
								+ uid[0] + "&tName=" + tname[0] + "&uAccess="
								+ uacc[0]);
			} else {
				out.println("<html>");
				out.println("  <head><title>Insert");
				out.println("  </title><link type=\"text/css\" rel=\"stylesheet\" href=\"main.css\"/></head>");
				out.println("  <body>");
				out.println("    <p>");
				out.println("    <center>");

				out.println("Fail");
				out.println(errorMessage);

				out.println("    </center>");
				out.println("    </p>");
				out.println("  </body>");
				out.println("</html>");
			}
			try {
				stmt1.close();
				stmt2.close();
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
			out.close();
		}
	}
